﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Reporting.WinForms;
using CommonHelper;
using CommonHelper.VersionCheckProxy;
using System.Diagnostics;
using System.IO;

namespace SQLIOSimParser
{
    public partial class Main : Form
    {
        bool ColorMessageText = true;

        private const string CONST_NOTIFY_WARNING_NOINTERNETCONNECION = "You seem not to have an active internet connection. Check for updates will be skipped.";
        private const string CONST_ERROR_NOCONTACT = "The update service could not be contacted, check your internet connection.";
        private const string CONST_NOTIFY_INFONOTNEWUPDATES = "No new updates available. You already have the most current version of SQLIOSimParser.";

        SQLIOSimParserWorker worker;
        DataSet dsResults;
        SQLIOSimParserSettings settings;

        public Main()
        {
            InitializeComponent();
            worker = new SQLIOSimParserWorker();
            worker.HandleMessageEvent += new SQLIOSimParserWorker.HandleMessage(WriteMessages);
            settings = new SQLIOSimParserSettings();
            InitializeControl();

            SQLIOSimParserWorker.PostProcessEvent(Constants.CONST_ACTION_START, new string[] { settings.ToString()});
        }

        private void InitializeControl()
        {
            txtDelimiter.Text = settings.ExportDelimiter;
            radioButton1.Checked = radioButton1.Tag.ToString() == settings.ExportType;
            radioButton2.Checked = radioButton2.Tag.ToString() == settings.ExportType;

            ToggleControlVisibility();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SQLIOSimParserWorker pw = new SQLIOSimParserWorker();
            dsResults = pw.ParseIOSimFile(txtInputFileName.Text);
        }


        public void WriteMessages(string Message, TraceLevel priority)
        {
            Message = string.Format("{0}:{1}", DateTime.Now.ToLongTimeString(), Message);
            string MessageString = string.Format("{0}\r\n", Message);
            rtbInformation.AppendText(MessageString);

            if (ColorMessageText == true)
            {
                Font fnt = new Font("Verdana", 8F, FontStyle.Regular, GraphicsUnit.Point);

                int FirstPosition = rtbInformation.Find(Message);

                if (FirstPosition == -1)
                    return;

                rtbInformation.SelectionStart = FirstPosition;
                rtbInformation.SelectionLength = Message.Length;
                rtbInformation.SelectionFont = fnt;

                switch (priority)
	            {
		            case TraceLevel.Error:
                        rtbInformation.SelectionColor = Color.Red;
                        break;
                    case TraceLevel.Info:
                        rtbInformation.SelectionColor = Color.DarkBlue;
                        break;
                    case TraceLevel.Off:
                        rtbInformation.SelectionColor = Color.Black;
                        break;
                    case TraceLevel.Verbose:
                        rtbInformation.SelectionColor = Color.Black;
                        break;
                    case TraceLevel.Warning:
                        rtbInformation.SelectionColor = Color.Orange;
                        break;
                    default:
                     break;
                }
            }
        }

        public enum Priority
        {
            Informational,
            Success,
            Error,
            Critical,
            Unknown
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            CheckForVersionUpdates(WebHelper.UpdateCheckType.Start);
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox ab = new AboutBox();
            ab.ShowDialog();
        }

        private void checkForUpdatesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CheckForVersionUpdates(WebHelper.UpdateCheckType.Adhoc);
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void CheckForVersionUpdates(WebHelper.UpdateCheckType updateCheckType)
        {
            if (!CommonHelper.NetHelper.IsConnectedToInternet())
            {
                WriteMessages(CONST_NOTIFY_WARNING_NOINTERNETCONNECION, TraceLevel.Error);
                return;
            }

            string SoftwareUpdateUrl = Properties.Settings.Default.SoftwareUpdateUrl;
            CommonHelper.VersionCheckProxy.VersionCheckResponse resp = CommonHelper.WebHelper.GetCurrentVersionInformation(SoftwareUpdateUrl, updateCheckType, AssemblyAccessors.AssemblyGuidString, AssemblyAccessors.AssemblyVersion);

            if (!string.IsNullOrEmpty(resp.Error))
            {
                WriteMessages(CONST_ERROR_NOCONTACT, TraceLevel.Error);
            }
            else
            {
                if (CommonHelper.WebHelper.UpdateAvailable(resp.VersionNumber, AssemblyAccessors.AssemblyVersion))
                {
                    WriteMessages(string.Format("A new version is available (Version: {0}, Published: {1}).", resp.VersionNumber, resp.PublishDate), TraceLevel.Info);
                    AvailableUpdateForm av = new AvailableUpdateForm(AssemblyAccessors.AssemblyVersion,resp);
                    av.ShowDialog();
                }
                else
                {
                    WriteMessages(string.Format(CONST_NOTIFY_INFONOTNEWUPDATES, resp.Error), TraceLevel.Info);
                }
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtInputFileName.Text))
                openFileDialog1.InitialDirectory = txtInputFileName.Text;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                txtInputFileName.Text = openFileDialog1.FileName;
                ParseInpuFile();
            }


        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                txtOutputFileName.Text = saveFileDialog1.FileName;
            }
        }

        private void btnParseFile_Click(object sender, EventArgs e)
        {
            ParseInpuFile();
        }

        private void ParseInpuFile()
        {
            try
            {
                dsResults = worker.ParseIOSimFile(txtInputFileName.Text);

                if (dsResults == null)
                    return;

                ToggleControlVisibility();

                ResultsPane pane = new ResultsPane(dsResults);
                pane.ShowDialog();

                txtOutputFileName.Text = string.Format("{0}{1}", txtInputFileName.Text, ".csv");
            }
            catch (Exception ex)
            {
                WriteMessages(string.Format("Error during parsing, file is not valid, see exception for more details --> {0}", ex.Message), TraceLevel.Error);
            }

        }

        private void ToggleControlVisibility()
        {
            groupBox2.Enabled = dsResults != null;
            
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            try
            {
                if (radioButton1.Checked)
                    worker.ExportResultFileToXML(txtOutputFileName.Text);

                if (radioButton2.Checked)
                {
                    worker.ExportResultFileToCsv(txtOutputFileName.Text, txtDelimiter.Text);
                }

                if(MessageBox.Show("Open exported file ?", "Export file",MessageBoxButtons.YesNo,MessageBoxIcon.Question) == DialogResult.Yes)
                    System.Diagnostics.Process.Start(txtOutputFileName.Text);
            }
            catch (Exception ex)
            {
                WriteMessages(ex.Message, TraceLevel.Error);
            }
        }

        private void btnDisplayReport_Click(object sender, EventArgs e)
        {
            AdditionalReportInfo ad = new AdditionalReportInfo(dsResults);
            ad.ShowDialog();
        }

        private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Settings settingsform = new Settings();
            settingsform.ShowDialog();

            settings = settingsform.SQLIOSimParserSettings;
            InitializeControl();
        }
    }
}
